package com.meituan.service.impl;

import com.meituan.dao.RoleRepository;
import com.meituan.dao.UserRepository;
import com.meituan.dao.UserRoleMapper;
import com.meituan.pojo.entity.Role;
import com.meituan.pojo.entity.User;
import com.meituan.pojo.req.UserReq;
import com.meituan.pojo.req.UserRoleReq;
import com.meituan.pojo.resp.BasePermissionResp;
import com.meituan.pojo.resp.BasePermissionValueResp;
import com.meituan.pojo.resp.BaseResp;
import com.meituan.service.UserService;
import com.meituan.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    UserRoleMapper userRoleMapper;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    JavaMailSender javaMailSender;

    @Override
    public BaseResp login(UserReq UserReq) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(UserReq.getUsername(), UserReq.getPassword());
        try {
            subject.login(usernamePasswordToken);
        }catch (UnknownAccountException unknownAccountException){
            return new BaseResp(0,"账户名输入错误",null);
        }catch (IncorrectCredentialsException incorrectCredentialsException){
            return new BaseResp(0,"密码输入错误！",null);
        }
        return new BaseResp().SUCCESS();
    }

    @Override
    public BaseResp regist(UserReq UserReq, HttpSession session) {
        Object attribute = session.getAttribute(UserReq.getEmail());
        if (attribute==null){
            return new BaseResp(0,"未发送验证码！请先发送！",null);
        }
        if (!UserReq.getCode().equals(attribute)){
            return new BaseResp(0,"验证码比对失败！",null);
        }
        User User =  userRepository.findByUsername(UserReq.getUsername());
        if (User!=null){
            return new BaseResp(0,"账户名已重复！",null);
        }
        User user = new User();
        BeanUtils.copyProperties(UserReq,user);
        String md5 = MD5Utils.createMD5(user.getUsername(), user.getPassword());
        user.setPassword(md5);
        userRepository.save(user);
        return new BaseResp().SUCCESS();
    }

    @Override
    public BaseResp sendMail(String email, HttpSession session) {
        User tbUser =  userRepository.findByEmail(email);
        if (tbUser!=null){
            return new BaseResp(0,"此邮箱已被注册！",null);
        }
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(email);
        simpleMailMessage.setSubject("美团注册邮件");
        StringBuffer stringBuffer = new StringBuffer();
        for (int i=0;i<6;i++){
            stringBuffer.append(new Random().nextInt(10));
        }
        simpleMailMessage.setText("【美团】您正在注册美团平台，您的平台验证码为"+stringBuffer.toString()+"，此验证码5分钟内有效。");
//        simpleMailMessage.setText("【美团】您正在注册美团平台，您的平台验证码为675781"+"，此验证码5分钟内有效。");
        try{
            javaMailSender.send(simpleMailMessage);
            session.setAttribute(email,stringBuffer.toString());
            return new BaseResp().SUCCESS();
        }catch (Exception e){
            return new BaseResp().ERROR();
        }
    }

    @Override
    public BaseResp findAll() {
        List<User> all = userRepository.findAll();
        return new BaseResp(1,"success",all);
    }

    @Override
    public BaseResp deleteById(Integer id) {
        userRepository.deleteById(id);
        return new BaseResp().SUCCESS();
    }

    @Override
    public BaseResp saveOrUpdate(UserReq userReq) {
        User user = new User();
        BeanUtils.copyProperties(userReq,user);
        String md5 = MD5Utils.createMD5(userReq.getUsername(),userReq.getPassword());
        if (userReq.getId()!=null){
            Optional<User> byId = userRepository.findById(userReq.getId());
            User user1 = byId.get();
            if (!md5.equals(user1.getPassword())){
                user.setPassword(md5);
            }
        }else{
            user.setPassword(md5);
        }
        userRepository.saveAndFlush(user);
        return new BaseResp().SUCCESS();
    }

    @Override
    public BaseResp findRoleByUid(Integer id) {
        List<Role> all = roleRepository.findAll();
        List roleList = new ArrayList();
        for (Role role:all){
            BasePermissionResp basePermissionResp = new BasePermissionResp();
            basePermissionResp.setKey(role.getRid());
            basePermissionResp.setLabel(role.getRoleName());
            basePermissionResp.setDisable(false);
            roleList.add(basePermissionResp);
        }
        List<Integer> ridByUid = roleRepository.findRidByUid(id);
        BasePermissionValueResp basePermissionValueResp = new BasePermissionValueResp();
        basePermissionValueResp.setData(roleList);
        basePermissionValueResp.setValue(ridByUid);
        return new BaseResp(1,"success",basePermissionValueResp);
    }

    @Override
    public BaseResp updateUserRole(UserRoleReq userRoleReq) {
        List<Integer> rid = userRoleReq.getRid();

        List<Integer> rids = userRoleMapper.selectUid(userRoleReq.getUid());
        if (rids!=null&&rids.size()>0){
            userRoleMapper.deleteByUid(userRoleReq.getUid());
        }
        if (rid!=null&&rid.size()>0){
            userRoleMapper.addUserRole(userRoleReq);
        }
        return new BaseResp().SUCCESS();
    }

    @Override
    public User findUserByUserName(String userName) {
        User byUsername = userRepository.findByUsername(userName);
        return byUsername;
    }
}
